package com.template.utils.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 去重复统计功能的基数估计算法
 * HyperLogLog 本质是 String 类型
 */
@Component
public class HyperLogLogOps extends KeyOps {

    private final HyperLogLogOperations<String, Object> hyperLogLogOperations;

    @Autowired
    public HyperLogLogOps(RedisTemplate<String, Object> redisTemplate) {
        super(redisTemplate);
        this.hyperLogLogOperations = redisTemplate.opsForHyperLogLog();
    }

    /**
     * <h4> Hyper Log Log </h4>
     * 添加指定元素到 HyperLogLog 中
     * <li> pfadd _key _value1 _value2 ... </li>
     */
    public Long pfAdd(String key, Object... values) {
        return hyperLogLogOperations.add(key, values);
    }

    /**
     * <h4> Hyper Log Log </h4>
     * 获取给定 HyperLogLog 的基数估算值
     * <li> pfcount _key1 _key2 ... </li>
     */
    public Long pfCount(String... keys) {
        return hyperLogLogOperations.size(keys);
    }

    /**
     * <h4> Hyper Log Log </h4>
     * 将多个 HyperLogLog 合并为一个
     * <li> pfcount _newKey _key1 _key2 ... </li>
     */
    public Long pfMerge(String newKey, String... keys) {
        return hyperLogLogOperations.union(newKey, keys);
    }

    /**
     * <h4> Hyper Log Log </h4>
     * 删除
     * <li> pfcount _newKey _key1 _key2 ... </li>
     */
    public void pfRem(String key) {
        hyperLogLogOperations.delete(key);
    }
}
